
#include "main.h"

#define   SMS_MESSAGE_SIZE		164

unsigned char SMS_Message[SMS_MESSAGE_SIZE];

enum
{
	PRINT_SMS = 200,
	TIMER,
	GET_LIST_OF_NEW_SMS,
	READ_SMS,
	PAUSE,
	DELETE_SMS,
	GET_SMS_NUMBER	
};

#define   SMS_READ_PERIOD					5
#define   HOW_MANY_TIMES_TO_PRINT		2

void Print_SMS ( void )
{
	static unsigned char State = ST_START, Timer, SMS_Amount, SMS_Number, SMS_Index, ErrCnt;
	unsigned char Result, pt;

	switch( State )
	{
		case ST_START:
			putsf("\n\n\n\n SMS PRINT DEVICE: START\n\n\n\n\n\n\n", AUX_PORT);
			No_Delete_SMS_For_User = TRUE;

		case ST_RESET:
			Timer = SMS_READ_PERIOD;
			ErrCnt = 3;
			SMS_Amount = 0;
			SMS_Index = 0;
			State = IDLE;
			Debug("\n Timer: %d", Timer);
			break;

		case IDLE:
			if ( User_Message )
			{
				State = GET_LIST_OF_NEW_SMS;
			}
			else
				if ( InputsEvent == INPUT_6_DOWN )
				{
					State = PRINT_SMS;
				}
			break;
 	
		case GET_LIST_OF_NEW_SMS:
			Result = SMS_Get_List("READ", SMS_User_Messages_List);
			
			if ( Result != BUSY )
			{
				if ( Result == MODEM_ERROR )
				{
					//Debug("\n\n\n MODEM_ERROR: ", MODEM_ERROR);
					State = ST_RESET;
				}
				else
				{
					SMS_Amount = Result;
					//Debug("\n SMS_Amount: ", SMS_Amount);
					State = GET_SMS_NUMBER;
				}
			}
			break;

		case GET_SMS_NUMBER:
			if ( SMS_Amount )
			{
				SMS_Amount--;
				SMS_Number = SMS_User_Messages_List[SMS_Index++];
				State = READ_SMS;
			}
			else
			{
				/* delete all SMS after the printing */
				if ( SMS_Index )
				{
					State = DELETE_SMS;
				}
				else
				{
					State = ST_RESET;
				}
			}
			break;

		case READ_SMS:
			Result = SMS_Read(SMS_Message, SMS_Number, BUSY_APP_PRINT_SMS);
			if ( Result != BUSY )
			{
				if ( Result == FALSE )
				{
					Debug("\n\n READ_SMS_ERROR: %d", -1);
					State = GET_SMS_NUMBER;
				}
				else
				{
					State = PRINT_SMS;
				}
			}
			break;

		case PRINT_SMS:
			for ( pt = 0; pt < HOW_MANY_TIMES_TO_PRINT; pt++ )
		   {
				putsf("\n\n------------------------", AUX_PORT);
				putsf("\n DATE: ", AUX_PORT);
				puts(SMS_Header.Field.DateTime, AUX_PORT);
				putsf("\n From: ", AUX_PORT);
				puts(SMS_Header.Field.PhoneNumber, AUX_PORT);
				putsf("\n\n", AUX_PORT);
				StrReplaceCharAll(SMS_Message, '\r', '\n');
				puts(SMS_Message, AUX_PORT);
				putsf("\n\n------------------------\n\n\n", AUX_PORT);
			}

			putsf("\n\n------------------------\n\n\n\n\n", AUX_PORT);
			
			State = PAUSE;
			Timer = 8;
			break;	

		case PAUSE:
			if ( Time_100ms && --Timer == 0 )
			{
				State = GET_SMS_NUMBER;
			} 
			break;


		case DELETE_SMS:
			if ( SendToModem("AT+CMGDA=\"DEL READ\"\r", STR__OK, BUSY_APP_PRINT_SMS) != BUSY )
			{
				State = ST_RESET;
			}
			break;
	
		default:
			State = ST_RESET;
	}
}
